/*
 * @Author       : 邱狮杰
 * @Date         : 2021-05-19 14:18:34
 * @LastEditTime : 2021-05-20 16:30:32
 * @FilePath     : /wedding-dress-selection/src/reducer/userInfo.tsx
 * @Description  : user info
 */

import { createContext, Dispatch, useReducer } from 'react'
import { setLocal, getLocal } from '../utils/index'

export const CreateUserInfo = createContext({})
export const OPENID = 'openId'
export const INVITATIONID = 'invitation_id'
export const GETINFO = 'getInfo'
export const RESET = 'reset'
export const EDITLIKES = 'editLikes'
export const LIKESADD = 'likesAdd'
interface StateConfig {
  openId: string | null
  invitationId: string | null
  likes: string[]
}

interface Action {
  type: typeof GETINFO | typeof RESET | typeof EDITLIKES | typeof LIKESADD
  data?: StateConfig | string[] | string
}
export interface useContextUserInfoType {
  userInfoState: StateConfig
  userInfoDispatch: Dispatch<Action>
}
const initState: StateConfig = {
  openId: getLocal(OPENID) || setLocal(OPENID, ''),
  invitationId: getLocal(INVITATIONID) || setLocal(INVITATIONID, ''),
  likes: [],
}

function reducerUserInfo(state: StateConfig, action: Action) {
  switch (action.type) {
    case GETINFO:
      return state
    case RESET:
      return Object.assign(state, action.data)
    case EDITLIKES:
      state.likes = action.data as string[]
      return state
    case LIKESADD:
      state.likes = Array.from(new Set(state.likes).add(action.data as string))
      return state
    default:
      return state
  }
}

export const UserInfoContext = (props: any) => {
  const [userInfoState, userInfoDispatch] = useReducer(reducerUserInfo, initState)
  return <CreateUserInfo.Provider value={{ userInfoState, userInfoDispatch }}>{props.children}</CreateUserInfo.Provider>
}
